<template>
  <div class="register-modal-overlay" @click="closeModal">
    <div class="register-modal" @click.stop>
      <button class="close-btn" @click="closeModal">×</button>

      <h2>用户注册</h2>

      <!-- 注册步骤指示器 -->
      <div class="step-indicator">
        <div :class="['step', { active: currentStep === 1 }]">1. 选择角色</div>
        <div :class="['step', { active: currentStep === 2 }]">2. 填写信息</div>
        <div v-if="formData.role === 'parent'" :class="['step', { active: currentStep === 3 }]">3. 儿童信息</div>
      </div>

      <div class="register-form">
        <!-- 步骤1: 选择角色 -->
        <div v-if="currentStep === 1" class="step-content">
          <h3>请选择您的角色</h3>
          <div class="role-options">
            <label class="role-option" @click="selectRole('teacher')">
              <input type="radio" v-model="formData.role" value="teacher" hidden>
              <div class="role-card" :class="{ selected: formData.role === 'teacher' }">
                <div class="role-icon">👩‍🏫</div>
                <div class="role-info">
                  <h4>教师</h4>
                  <p>管理班级教学，关注学生成长</p>
                </div>
              </div>
            </label>

            <label class="role-option" @click="selectRole('parent')">
              <input type="radio" v-model="formData.role" value="parent" hidden>
              <div class="role-card" :class="{ selected: formData.role === 'parent' }">
                <div class="role-icon">👨‍👩‍👧‍👦</div>
                <div class="role-info">
                  <h4>家长</h4>
                  <p>管理孩子学习，查看学习进度</p>
                </div>
              </div>
            </label>

            <label v-if="showAdminOption" class="role-option" @click="selectRole('admin')">
              <input type="radio" v-model="formData.role" value="admin" hidden>
              <div class="role-card" :class="{ selected: formData.role === 'admin' }">
                <div class="role-icon">🔐</div>
                <div class="role-info">
                  <h4>管理员</h4>
                  <p>系统管理，权限配置</p>
                </div>
              </div>
            </label>
          </div>

          <button type="button" class="btn-next" @click="nextStep" :disabled="!formData.role">
            下一步
          </button>
        </div>

        <!-- 步骤2: 基本信息 -->
        <div v-if="currentStep === 2" class="step-content">
          <h3>填写基本信息</h3>

          <div class="form-group">
            <label>用户名 *</label>
            <input
              v-model="formData.username"
              type="text"
              placeholder="请输入用户名（4-20位字母、数字或下划线）"
              required
              @blur="checkUsername"
              :class="{ error: usernameStatus === 'error' }"
            >
            <div v-if="usernameStatus" class="status-message" :class="usernameStatus">
              {{ usernameMessage }}
            </div>
          </div>

          <div class="form-group">
            <label>密码 *</label>
            <input
              v-model="formData.password"
              type="password"
              placeholder="请输入密码（8-20位，包含字母和数字）"
              required
              @input="validatePassword"
              :class="{ error: passwordStatus === 'error' }"
            >
            <div v-if="passwordStatus" class="status-message" :class="passwordStatus">
              {{ passwordMessage }}
            </div>
            <div class="password-strength" v-if="formData.password">
              <div class="strength-bar" :class="passwordStrength"></div>
              <span class="strength-text">{{ getPasswordStrengthText() }}</span>
            </div>
          </div>

          <div class="form-group">
            <label>确认密码 *</label>
            <input
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              required
              @input="validateConfirmPassword"
              :class="{ error: confirmPasswordStatus === 'error' }"
            >
            <div v-if="confirmPasswordStatus" class="status-message" :class="confirmPasswordStatus">
              {{ confirmPasswordMessage }}
            </div>
          </div>

          <div class="form-group">
            <label>昵称</label>
            <input
              v-model="formData.nickname"
              type="text"
              placeholder="请输入昵称（2-20位字符）"
              @input="validateNickname"
              :class="{ error: nicknameStatus === 'error' }"
            >
            <div v-if="nicknameStatus" class="status-message" :class="nicknameStatus">
              {{ nicknameMessage }}
            </div>
          </div>

          <div class="form-group">
            <label>邮箱</label>
            <input
              v-model="formData.email"
              type="email"
              placeholder="请输入邮箱地址"
              @blur="validateEmail"
              :class="{ error: emailStatus === 'error' }"
            >
            <div v-if="emailStatus" class="status-message" :class="emailStatus">
              {{ emailMessage }}
            </div>
          </div>

          <div class="form-group">
            <label>手机号</label>
            <input
              v-model="formData.phone"
              type="tel"
              placeholder="请输入手机号"
              @blur="validatePhone"
              :class="{ error: phoneStatus === 'error' }"
            >
            <div v-if="phoneStatus" class="status-message" :class="phoneStatus">
              {{ phoneMessage }}
            </div>
          </div>

          <div class="form-group">
            <label>验证码 *</label>
            <div class="captcha-container">
              <input
                v-model="formData.captcha"
                type="text"
                placeholder="请输入验证码"
                required
                class="captcha-input"
                maxlength="4"
                :class="{ error: !formData.captcha && currentStep === 2 }"
              >
              <div class="captcha-image-wrapper">
                <img
                  v-if="captchaImage"
                  :src="captchaImage"
                  alt="验证码"
                  class="captcha-image"
                  @click="refreshCaptcha"
                  title="点击刷新验证码"
                >
                <div v-else class="captcha-loading">加载中...</div>
              </div>
            </div>
          </div>

          <div class="form-actions">
            <button type="button" class="btn-prev" @click="prevStep">上一步</button>
            <button 
              v-if="formData.role === 'parent'" 
              type="button" 
              class="btn-next" 
              :disabled="loading || !isStep2Valid"
              @click="handleRegister"
            >
              下一步
            </button>
            <button 
              v-else 
              type="button" 
              class="btn-next" 
              :disabled="loading || !isStep2Valid"
              @click="handleRegister"
            >
              注册
            </button>
          </div>
        </div>

        <!-- 步骤3: 儿童信息 (仅家长) -->
        <div v-if="currentStep === 3 && formData.role === 'parent'" class="step-content">
          <h3>填写儿童信息</h3>
          <p class="step-description">请为您的孩子创建学习账户</p>

          <div class="form-group">
            <label>儿童用户名 *</label>
            <input
              v-model="childFormData.username"
              type="text"
              placeholder="请输入儿童用户名（4-20位字母、数字或下划线）"
              required
              @blur="checkChildUsername"
              :class="{ error: childUsernameStatus === 'error' }"
            >
            <div v-if="childUsernameStatus" class="status-message" :class="childUsernameStatus">
              {{ childUsernameMessage }}
            </div>
          </div>

          <div class="form-group">
            <label>儿童昵称</label>
            <input
              v-model="childFormData.nickname"
              type="text"
              placeholder="请输入儿童昵称（2-20位字符）"
              @input="validateChildNickname"
              :class="{ error: childNicknameStatus === 'error' }"
            >
            <div v-if="childNicknameStatus" class="status-message" :class="childNicknameStatus">
              {{ childNicknameMessage }}
            </div>
          </div>

          <div class="form-group">
            <label>儿童密码 *</label>
            <input
              v-model="childFormData.password"
              type="password"
              placeholder="请输入儿童密码（8-20位，包含字母和数字）"
              required
              @input="validateChildPassword"
              :class="{ error: childPasswordStatus === 'error' }"
            >
            <div v-if="childPasswordStatus" class="status-message" :class="childPasswordStatus">
              {{ childPasswordMessage }}
            </div>
          </div>

          <div class="form-group">
            <label>确认密码 *</label>
            <input
              v-model="childFormData.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              required
              @input="validateChildConfirmPassword"
              :class="{ error: childConfirmPasswordStatus === 'error' }"
            >
            <div v-if="childConfirmPasswordStatus" class="status-message" :class="childConfirmPasswordStatus">
              {{ childConfirmPasswordMessage }}
            </div>
          </div>

          <div class="form-group">
            <label>儿童年龄 *</label>
            <select v-model="childFormData.age" required @change="validateAge">
              <option value="">请选择年龄</option>
              <option v-for="age in 12" :key="age" :value="age + 2">{{ age + 2 }}岁</option>
            </select>
            <div v-if="ageStatus" class="status-message" :class="ageStatus">
              {{ ageMessage }}
            </div>
          </div>

          <div class="form-group">
            <label>英语基础 *</label>
            <select v-model="childFormData.englishLevel" required>
              <option value="">请选择英语水平</option>
              <option value="beginner">零基础</option>
              <option value="intermediate">有基础</option>
              <option value="advanced">熟练</option>
            </select>
          </div>

          <div class="form-group">
            <label>兴趣爱好</label>
            <input
              v-model="childFormData.interests"
              type="text"
              placeholder="如：动物、音乐、运动等"
              @input="validateInterests"
              :class="{ error: interestsStatus === 'error' }"
            >
            <div v-if="interestsStatus" class="status-message" :class="interestsStatus">
              {{ interestsMessage }}
            </div>
          </div>

          <!-- 班级分配信息只在注册成功后显示 -->
          <div v-if="showSuccess && assignedClass" class="class-assignment">
            <div class="assignment-card">
              <div class="assignment-icon">🎒</div>
              <div class="assignment-info">
                <h4>班级分配</h4>
                <p>根据儿童年龄，已分配到: <strong>{{ assignedClass }}</strong></p>
              </div>
            </div>
          </div>

          <div class="form-actions">
            <button type="button" class="btn-prev" @click="prevStep">上一步</button>
            <button type="button" class="btn-register" :disabled="loading || !isStep3Valid" @click="handleRegister">
              {{ loading ? '注册中...' : '完成注册' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 注册成功提示 -->
      <div v-if="showSuccess" class="success-message">
        <div class="success-content">
          <div class="success-icon">✅</div>
          <div class="success-text">
            <h3>注册成功！</h3>
            <p>{{ successMessage }}</p>
            <button class="btn-login" @click="goToLogin">立即登录</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { childEnglishApi } from '../api/childEnglishApi'
import { encrypt } from '../utils/encryption'

export default {
  name: 'RegisterModal',
  emits: ['close', 'register-success', 'show-login'],
  data() {
    return {
      currentStep: 1,
      loading: false,
      showSuccess: false,
      successMessage: '',
      assignedClass: '',

      // 表单数据
      formData: {
        role: '',
        username: '',
        password: '',
        confirmPassword: '',
        nickname: '',
        email: '',
        phone: '',
        captcha: ''
      },
      captchaImage: '',

      childFormData: {
        username: '',
        password: '',
        confirmPassword: '',
        nickname: '',
        age: '',
        englishLevel: '',
        interests: ''
      },

      // 验证状态
      usernameStatus: '',
      usernameMessage: '',

      passwordStatus: '',
      passwordMessage: '',
      passwordStrength: '',

      confirmPasswordStatus: '',
      confirmPasswordMessage: '',

      nicknameStatus: '',
      nicknameMessage: '',

      emailStatus: '',
      emailMessage: '',

      phoneStatus: '',
      phoneMessage: '',

      childUsernameStatus: '',
      childUsernameMessage: '',

      childPasswordStatus: '',
      childPasswordMessage: '',

      childConfirmPasswordStatus: '',
      childConfirmPasswordMessage: '',

      childNicknameStatus: '',
      childNicknameMessage: '',

      ageStatus: '',
      ageMessage: '',

      interestsStatus: '',
      interestsMessage: '',

      parentUser: null
    }
  },
  mounted() {
    // 组件挂载时获取验证码
    this.refreshCaptcha();
  },
  computed: {
    showAdminOption() {
      return process.env.NODE_ENV === 'development'
    },
    isStep2Valid() {
      return (
        this.formData.username &&
        this.formData.password &&
        this.formData.confirmPassword &&
        this.formData.password === this.formData.confirmPassword &&
        this.usernameStatus === 'success' &&
        this.passwordStatus === 'success' &&
        (!this.formData.email || this.emailStatus !== 'error') &&
        (!this.formData.phone || this.phoneStatus !== 'error') &&
        (!this.formData.nickname || this.nicknameStatus !== 'error')
      )
    },
    isStep3Valid() {
      return (
        this.childFormData.username &&
        this.childFormData.password &&
        this.childFormData.confirmPassword &&
        this.childFormData.password === this.childFormData.confirmPassword &&
        this.childFormData.age &&
        this.childFormData.englishLevel &&
        this.childUsernameStatus === 'success' &&
        this.childPasswordStatus === 'success' &&
        (!this.childFormData.nickname || this.childNicknameStatus !== 'error') &&
        (!this.childFormData.interests || this.interestsStatus !== 'error')
      )
    }
  },
  methods: {
    closeModal() {
      this.$emit('close')
    },

    selectRole(role) {
      this.formData.role = role
    },

    nextStep() {
      if (this.currentStep === 1 && this.formData.role) {
        this.currentStep = 2
      } else if (this.currentStep === 2 && this.formData.role === 'parent') {
        this.currentStep = 3
      }
    },

    prevStep() {
      if (this.currentStep > 1) this.currentStep--
    },

    // 获取验证码
    async refreshCaptcha() {
      try {
        const response = await childEnglishApi.getCaptcha();
        if (response.code === 200 && response.data) {
          this.captchaImage = response.data.image;
          // 清空验证码输入框
          this.formData.captcha = '';
        } else {
          console.error('获取验证码失败:', response.message);
          alert('获取验证码失败，请刷新页面重试');
        }
      } catch (error) {
        console.error('获取验证码错误:', error);
        alert('获取验证码失败: ' + (error.response?.data?.message || error.message));
      }
    },

    // 用户名验证
    async checkUsername() {
      if (!this.formData.username?.trim()) {
        this.usernameStatus = 'error';
        this.usernameMessage = '用户名不能为空';
        return;
      }

      const username = this.formData.username.trim();

      // 用户名格式验证
      const usernameRegex = /^[a-zA-Z0-9_]{4,20}$/;
      if (!usernameRegex.test(username)) {
        this.usernameStatus = 'error';
        this.usernameMessage = '用户名必须为4-20位字母、数字或下划线';
        return;
      }

      console.log('【调试】检查用户名：', username);

      // 直接返回成功，不进行实际API调用
      this.usernameStatus = 'success';
      this.usernameMessage = '用户名可用';
    },

    // 密码验证
    validatePassword() {
      if (!this.formData.password) {
        this.passwordStatus = 'error';
        this.passwordMessage = '密码不能为空';
        this.passwordStrength = '';
        return;
      }

      const password = this.formData.password;

      // 密码强度验证
      if (password.length < 8 || password.length > 20) {
        this.passwordStatus = 'error';
        this.passwordMessage = '密码长度必须为8-20位';
        this.passwordStrength = 'weak';
        return;
      }

      // 检查是否包含字母和数字
      const hasLetter = /[a-zA-Z]/.test(password);
      const hasNumber = /[0-9]/.test(password);

      if (!hasLetter || !hasNumber) {
        this.passwordStatus = 'error';
        this.passwordMessage = '密码必须包含字母和数字';
        this.passwordStrength = 'medium';
        return;
      }

      // 计算密码强度
      let strength = 0;
      if (password.length >= 8) strength++;
      if (hasLetter && hasNumber) strength++;
      if (/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password)) strength++;
      if (password.length >= 12) strength++;

      this.passwordStatus = 'success';
      this.passwordMessage = '密码强度合适';

      // 设置密码强度等级
      if (strength <= 2) {
        this.passwordStrength = 'weak';
      } else if (strength === 3) {
        this.passwordStrength = 'medium';
      } else {
        this.passwordStrength = 'strong';
      }

      // 验证确认密码
      if (this.formData.confirmPassword) {
        this.validateConfirmPassword();
      }
    },

    getPasswordStrengthText() {
      switch (this.passwordStrength) {
        case 'weak': return '弱';
        case 'medium': return '中';
        case 'strong': return '强';
        default: return '';
      }
    },

    // 确认密码验证
    validateConfirmPassword() {
      if (!this.formData.confirmPassword) {
        this.confirmPasswordStatus = 'error';
        this.confirmPasswordMessage = '请确认密码';
        return;
      }

      if (this.formData.password !== this.formData.confirmPassword) {
        this.confirmPasswordStatus = 'error';
        this.confirmPasswordMessage = '两次密码输入不一致';
        return;
      }

      this.confirmPasswordStatus = 'success';
      this.confirmPasswordMessage = '密码匹配';
    },

    // 昵称验证
    validateNickname() {
      if (!this.formData.nickname) {
        this.nicknameStatus = '';
        this.nicknameMessage = '';
        return;
      }

      const nickname = this.formData.nickname.trim();

      if (nickname.length < 2 || nickname.length > 20) {
        this.nicknameStatus = 'error';
        this.nicknameMessage = '昵称长度必须为2-20位';
        return;
      }

      this.nicknameStatus = 'success';
      this.nicknameMessage = '昵称格式正确';
    },

    // 邮箱验证
    validateEmail() {
      if (!this.formData.email) {
        this.emailStatus = '';
        this.emailMessage = '';
        return;
      }

      const email = this.formData.email.trim();
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

      if (!emailRegex.test(email)) {
        this.emailStatus = 'error';
        this.emailMessage = '请输入有效的邮箱地址';
        return;
      }

      this.emailStatus = 'success';
      this.emailMessage = '邮箱格式正确';
    },

    // 手机号验证
    validatePhone() {
      if (!this.formData.phone) {
        this.phoneStatus = '';
        this.phoneMessage = '';
        return;
      }

      const phone = this.formData.phone.trim();
      const phoneRegex = /^1[3-9]\d{9}$/;

      if (!phoneRegex.test(phone)) {
        this.phoneStatus = 'error';
        this.phoneMessage = '请输入有效的手机号码';
        return;
      }

      this.phoneStatus = 'success';
      this.phoneMessage = '手机号格式正确';
    },

    // 儿童用户名验证
    async checkChildUsername() {
      if (!this.childFormData.username?.trim()) {
        this.childUsernameStatus = 'error';
        this.childUsernameMessage = '儿童用户名不能为空';
        return;
      }

      const username = this.childFormData.username.trim();

      // 用户名格式验证
      const usernameRegex = /^[a-zA-Z0-9_]{4,20}$/;
      if (!usernameRegex.test(username)) {
        this.childUsernameStatus = 'error';
        this.childUsernameMessage = '用户名必须为4-20位字母、数字或下划线';
        return;
      }

      // 直接返回成功，不进行实际API调用
      this.childUsernameStatus = 'success';
      this.childUsernameMessage = '用户名可用';
    },

    // 儿童密码验证
    validateChildPassword() {
      if (!this.childFormData.password) {
        this.childPasswordStatus = 'error';
        this.childPasswordMessage = '密码不能为空';
        return;
      }

      const password = this.childFormData.password;

      if (password.length < 8 || password.length > 20) {
        this.childPasswordStatus = 'error';
        this.childPasswordMessage = '密码长度必须为8-20位';
        return;
      }

      // 检查是否包含字母和数字
      const hasLetter = /[a-zA-Z]/.test(password);
      const hasNumber = /[0-9]/.test(password);

      if (!hasLetter || !hasNumber) {
        this.childPasswordStatus = 'error';
        this.childPasswordMessage = '密码必须包含字母和数字';
        return;
      }

      this.childPasswordStatus = 'success';
      this.childPasswordMessage = '密码强度合适';

      // 验证确认密码
      if (this.childFormData.confirmPassword) {
        this.validateChildConfirmPassword();
      }
    },

    // 儿童确认密码验证
    validateChildConfirmPassword() {
      if (!this.childFormData.confirmPassword) {
        this.childConfirmPasswordStatus = 'error';
        this.childConfirmPasswordMessage = '请确认密码';
        return;
      }

      if (this.childFormData.password !== this.childFormData.confirmPassword) {
        this.childConfirmPasswordStatus = 'error';
        this.childConfirmPasswordMessage = '两次密码输入不一致';
        return;
      }

      this.childConfirmPasswordStatus = 'success';
      this.childConfirmPasswordMessage = '密码匹配';
    },

    // 儿童昵称验证
    validateChildNickname() {
      if (!this.childFormData.nickname) {
        this.childNicknameStatus = '';
        this.childNicknameMessage = '';
        return;
      }

      const nickname = this.childFormData.nickname.trim();

      if (nickname.length < 2 || nickname.length > 20) {
        this.childNicknameStatus = 'error';
        this.childNicknameMessage = '昵称长度必须为2-20位';
        return;
      }

      this.childNicknameStatus = 'success';
      this.childNicknameMessage = '昵称格式正确';
    },

    // 年龄验证
    validateAge() {
      if (!this.childFormData.age) {
        this.ageStatus = 'error';
        this.ageMessage = '请选择儿童年龄';
        return;
      }

      const age = parseInt(this.childFormData.age);
      if (age < 3 || age > 14) {
        this.ageStatus = 'error';
        this.ageMessage = '年龄必须在3-14岁之间';
        return;
      }

      this.ageStatus = 'success';
      this.ageMessage = '年龄合适';
    },

    // 兴趣爱好验证
    validateInterests() {
      if (!this.childFormData.interests) {
        this.interestsStatus = '';
        this.interestsMessage = '';
        return;
      }

      const interests = this.childFormData.interests.trim();

      if (interests.length > 100) {
        this.interestsStatus = 'error';
        this.interestsMessage = '兴趣爱好不能超过100个字符';
        return;
      }

      this.interestsStatus = 'success';
      this.interestsMessage = '格式正确';
    },

    /* 提交注册 - 真正调用后端API */
    async handleRegister(event) {
      // 阻止默认表单提交行为
      if (event) {
        event.preventDefault();
        event.stopPropagation();
      }
      
      // 最终验证
      if (this.currentStep === 2 && !this.isStep2Valid) {
        alert('请正确填写所有必填信息');
        return;
      }

      if (this.currentStep === 3 && !this.isStep3Valid) {
        alert('请正确填写所有儿童信息');
        return;
      }

      this.loading = true

      try {
        if (this.formData.role === 'parent' && this.currentStep === 2) {
          // 验证码校验
          if (!this.formData.captcha || this.formData.captcha.trim() === '') {
            alert('请输入验证码');
            this.loading = false;
            return;
          }
          
          // 家长第一步注册
          const registerData = {
            username: this.formData.username,
            password: this.formData.password,
            confirmPassword: this.formData.confirmPassword,
            role: this.formData.role,
            nickname: this.formData.nickname || null,
            email: this.formData.email ? encrypt(this.formData.email.trim()) : null,
            phone: this.formData.phone ? encrypt(this.formData.phone.trim()) : null,
            captcha: this.formData.captcha
          }

          const response = await childEnglishApi.register(registerData)
          
          if (response && response.code === 200) {
            // 家长注册成功
            this.parentUser = {
              id: response.data.userId,
              username: response.data.username,
              role: response.data.role
            }

            // 清空之前预估的班级，等待后端实际分配
            this.assignedClass = ''

            this.currentStep = 3
            this.successMessage = '家长注册成功！请继续填写儿童信息'
          } else {
            alert(response?.message || response?.msg || '注册失败，请重试')
            // 注册失败后刷新验证码
            this.refreshCaptcha()
          }
        } else if (this.formData.role === 'parent' && this.currentStep === 3) {
          // 家长和儿童注册完成
          if (!this.parentUser || !this.parentUser.id) {
            alert('请先完成家长注册')
            return
          }

          const childRegisterData = {
            parentId: this.parentUser.id,
            childUsername: this.childFormData.username,
            childPassword: this.childFormData.password,
            confirmPassword: this.childFormData.confirmPassword,
            childNickname: this.childFormData.nickname || null,
            age: parseInt(this.childFormData.age),
            englishLevel: this.childFormData.englishLevel,
            interests: this.childFormData.interests || null
          }

          const response = await childEnglishApi.registerChild(childRegisterData)
          
          if (response && response.code === 200) {
            // 使用后端返回的实际分配的班级名称（来自数据库）
            const actualAssignedClass = response.data.assignedClass
            if (!actualAssignedClass) {
              console.warn('后端未返回分配的班级名称')
            }
            
            this.showSuccess = true
            this.assignedClass = actualAssignedClass || '未分配班级'
            this.successMessage = `家长和儿童注册成功！儿童已分配到 ${this.assignedClass}`

            // 保存用户数据，使用后端返回的实际班级信息
            const user = {
              id: this.parentUser.id,
              username: this.parentUser.username,
              role: this.parentUser.role,
              childInfo: {
                username: response.data.childUsername,
                nickname: this.childFormData.nickname || null,
                age: response.data.age,
                englishLevel: response.data.englishLevel,
                interests: response.data.interests,
                assignedClass: actualAssignedClass || '未分配班级',
                assignedClassId: response.data.assignedClassId || null
              }
            }

            // 只保存到sessionStorage，确保每个标签页独立会话
            const userData = JSON.stringify(user);
            sessionStorage.setItem('user', userData);
            this.$emit('register-success', user)

            setTimeout(() => this.closeModal(), 3000)
          } else {
            alert(response?.message || response?.msg || '儿童注册失败，请重试')
          }
        } else {
          // 验证码校验
          if (!this.formData.captcha || this.formData.captcha.trim() === '') {
            alert('请输入验证码');
            this.loading = false;
            return;
          }
          
          // 其他角色注册完成
          const registerData = {
            username: this.formData.username,
            password: this.formData.password,
            confirmPassword: this.formData.confirmPassword,
            role: this.formData.role,
            nickname: this.formData.nickname || null,
            email: this.formData.email ? encrypt(this.formData.email.trim()) : null,
            phone: this.formData.phone ? encrypt(this.formData.phone.trim()) : null,
            captcha: this.formData.captcha
          }

          const response = await childEnglishApi.register(registerData)
          
          if (response && response.code === 200) {
            this.showSuccess = true
            this.successMessage = '注册成功！'

            // 保存用户数据
            const user = {
              id: response.data.userId,
              username: response.data.username,
              role: response.data.role,
              nickname: this.formData.nickname,
              email: this.formData.email,
              phone: this.formData.phone
            }

            // 只保存到sessionStorage，确保每个标签页独立会话
            const userData = JSON.stringify(user);
            sessionStorage.setItem('user', userData);
            this.$emit('register-success', user)

            setTimeout(() => this.closeModal(), 3000)
          } else {
            alert(response?.message || response?.msg || '注册失败，请重试')
            // 注册失败后刷新验证码
            this.refreshCaptcha()
          }
        }
      } catch (error) {
        console.error('注册失败:', error)
        let errorMessage = '注册过程中出现错误，请重试'
        
        // 注册失败后刷新验证码
        this.refreshCaptcha()
        
        if (error.response) {
          // 服务器返回了错误响应
          errorMessage = error.response.data?.message || error.response.data?.msg || error.response.statusText || errorMessage
        } else if (error.request) {
          // 请求已发出但没有收到响应
          errorMessage = '网络错误，请检查网络连接'
        } else {
          // 其他错误
          errorMessage = error.message || errorMessage
        }
        
        alert(errorMessage)
      } finally {
        this.loading = false
      }
    },

    goToLogin() {
      this.closeModal()
      this.$emit('show-login')
    }
  }
}
</script>

<style scoped>
.register-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.register-modal {
  background: white;
  padding: 30px;
  border-radius: 15px;
  width: 500px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  pointer-events: auto;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

h2 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 20px;
}

.step-indicator {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  gap: 10px;
}

.step {
  padding: 8px 16px;
  background: #f8f9fa;
  border-radius: 20px;
  font-size: 14px;
  color: #6c757d;
  transition: all 0.3s ease;
}

.step.active {
  background: #3498db;
  color: white;
}

.step-content {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.role-options {
  display: grid;
  gap: 15px;
  margin-bottom: 20px;
}

.role-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.role-card:hover {
  border-color: #3498db;
  transform: translateY(-2px);
}

.role-card.selected {
  border-color: #3498db;
  background: #f0f8ff;
}

.role-icon {
  font-size: 2em;
  margin-right: 15px;
}

.role-info h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.role-info p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #2c3e50;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
  pointer-events: auto;
  position: relative;
  z-index: 1;
}

.form-group input:focus,
.form-group select:focus {
  border-color: #3498db;
  outline: none;
}

.form-group input.error {
  border-color: #e74c3c;
}

.status-message {
  margin-top: 5px;
  font-size: 14px;
}

.status-message.success {
  color: #27ae60;
}

.status-message.error {
  color: #e74c3c;
}

.status-message.warning {
  color: #f39c12;
}

/* 密码强度样式 */
.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.strength-bar {
  height: 4px;
  border-radius: 2px;
  flex: 1;
  transition: all 0.3s ease;
}

.strength-bar.weak {
  background: #e74c3c;
  width: 33%;
}

.strength-bar.medium {
  background: #f39c12;
  width: 66%;
}

.strength-bar.strong {
  background: #27ae60;
  width: 100%;
}

.strength-text {
  font-size: 12px;
  color: #7f8c8d;
  min-width: 20px;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.btn-prev, .btn-next, .btn-register {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-prev {
  background: #95a5a6;
  color: white;
}

.btn-prev:hover:not(:disabled) {
  background: #7f8c8d;
}

.btn-next, .btn-register {
  background: #3498db;
  color: white;
}

.btn-next:hover:not(:disabled),
.btn-register:hover:not(:disabled) {
  background: #2980b9;
  transform: translateY(-2px);
}

.btn-next:disabled,
.btn-register:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
  transform: none;
}

.step-description {
  color: #7f8c8d;
  text-align: center;
  margin-bottom: 20px;
}

.class-assignment {
  margin: 20px 0;
}

.assignment-card {
  display: flex;
  align-items: center;
  padding: 15px;
  background: #e8f5e8;
  border-radius: 8px;
  border-left: 4px solid #27ae60;
}

.assignment-icon {
  font-size: 24px;
  margin-right: 15px;
}

.assignment-info h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.assignment-info p {
  margin: 0;
  color: #27ae60;
}

.success-message {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 15px;
  z-index: 10;
  pointer-events: auto;
}

.success-content {
  text-align: center;
  padding: 20px;
}

.success-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.success-text h3 {
  color: #27ae60;
  margin-bottom: 10px;
}

.success-text p {
  color: #7f8c8d;
  margin-bottom: 20px;
}

.btn-login {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.btn-login:hover {
  background: #2980b9;
}

.register-form {
  /* 替代 form 标签的容器 */
}

.captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-input {
  flex: 1;
  width: auto;
  pointer-events: auto;
  position: relative;
  z-index: 1;
}

.captcha-image-wrapper {
  width: 120px;
  height: 40px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
}

.captcha-image-wrapper:hover {
  border-color: #3498db;
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  user-select: none;
}

.captcha-loading {
  color: #999;
  font-size: 12px;
}
</style>
